package com.lingshu.core.custom;

import android.content.Context;
import android.os.Environment;
import android.os.Looper;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Date;

/**
 * @author 于定金
 * @version 1.0
 * @Date 2024/1/4 11:33
 * @Description
 */
public class LocalFileHandler extends BaseExceptionHandler {

    private Context context;

    public LocalFileHandler(Context context) {
        this.context = context;
    }

    /**
     * 自定义错误处理，收集错误信息
     *
     * @param throwable
     * @return
     */
    @Override
    public boolean handlerException(Throwable throwable) {
        if (throwable == null)
            return false;
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(context, "很抱歉，程序出现异常", Toast.LENGTH_LONG).show();
            }
        }).start();
        saveLog(throwable);
        return true;
    }

    /**
     * 保存错误日志
     * @param throwable
     */
    private void saveLog(Throwable throwable) {
        try {
            File errorFile = new File(getDiskCacheDir(context) + "/log/crash.log");
            if (!errorFile.exists())
                errorFile.createNewFile();
            OutputStream outputStream = new FileOutputStream(errorFile, true);
            outputStream.write(("\n\n----------------错误分割线 " + DATE_FORMAT.format(new Date()) + "---------------------\n\n").getBytes());
            PrintStream stream = new PrintStream(outputStream);
            throwable.printStackTrace(stream);
            stream.flush();
            outputStream.flush();
            stream.close();
            outputStream.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 获取文件路径
     * @param context
     * @return
     */
    private String getDiskCacheDir(Context context) {
        String cachePath = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageEmulated()) {
            cachePath = context.getExternalCacheDir().getAbsolutePath();
        } else {
            cachePath = context.getCacheDir().getAbsolutePath();
        }
        return cachePath;
    }
}
